#include "attentionmodel.h"
#include <algorithm>

namespace yc {

AttentionModel::AttentionModel(QObject* parent) : QObject { parent } { }

AttentionModel::~AttentionModel()
{
    qDeleteAll(attentions_);
    attentions_.clear();
}

Attention* AttentionModel::attention(int id) const
{
    for (Attention* p : std::as_const(attentions_)) {
        if (p->id == id) {
            return p;
        }
    }
    return nullptr;
}

void AttentionModel::add(const Attention& attention)
{
    Attention* p = new Attention { attention };
    attentions_.push_back(p);
    Q_EMIT added(p, QPrivateSignal());
}

void AttentionModel::remove(int id)
{
    auto it = std::find_if(attentions_.constBegin(), attentions_.constEnd(),
                           [id](Attention* presenter) { return id == presenter->id; });
    if (it != attentions_.constEnd()) {
        Q_EMIT removed(*it, QPrivateSignal());
        delete *it;
        attentions_.erase(it);
    }
}

void AttentionModel::clear()
{
    if (!attentions_.empty()) {
        Q_EMIT modelAboutToBeReset(QPrivateSignal());
        qDeleteAll(attentions_);
        attentions_.clear();
        Q_EMIT modelReset(QPrivateSignal());
    }
}

Attention* AttentionModel::find(int presenter) const
{
    auto it = std::find_if(attentions_.constBegin(), attentions_.constEnd(),
                           [presenter](Attention* p) { return p->presenter == presenter; });
    return it != attentions_.constEnd() ? *it : nullptr;
}

int AttentionModel::autoCheckCount() const
{
    int count = 0;
    for (Attention* p : std::as_const(attentions_)) {
        if (p->auto_check) {
            ++count;
        }
    }
    return count;
}

int AttentionModel::autoRecordCount() const
{
    int count = 0;
    for (Attention* p : std::as_const(attentions_)) {
        if (p->auto_record) {
            ++count;
        }
    }
    return count;
}

void AttentionModel::setAutoCheck(int id, bool auto_check)
{
    if (auto p = attention(id)) {
        p->auto_check = auto_check;
        Q_EMIT changed(p, QPrivateSignal());
    }
}

void AttentionModel::setAutoRecord(int id, bool auto_record)
{
    if (auto p = attention(id)) {
        p->auto_record = auto_record;
        Q_EMIT changed(p, QPrivateSignal());
    }
}

void AttentionModel::setCategory(int id, bool category)
{
    if (auto p = attention(id)) {
        p->category = category;
        Q_EMIT changed(p, QPrivateSignal());
    }
}

} // namespace yc
